// Fill out your copyright notice in the Description page of Project Settings.


#include "Core/XGAudioCaptureSubsystem.h"

#include "AudioCapture.h"
#include "Log/FTLog.h"

bool UXGAudioCaptureSubsystem::ShouldCreateSubsystem(UObject* Outer) const
{
	return true;
}

void UXGAudioCaptureSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	Super::Initialize(Collection);
	AudioCapture = UAudioCaptureFunctionLibrary::CreateAudioCapture();
	if(AudioCapture)
	{
		AudioCapture->AddGeneratorDelegate(&UXGAudioCaptureSubsystem::OnAudioGenerated);

		if(InAudios.Num()>0)
		{
			for (auto& InAudio : InAudios)
			{
				delete InAudio;
				InAudio = nullptr;
			}
			InAudios.Empty();
		}
	}
	else
	{
		LOG_WITH_LOCATION_ERROR(TEXT("CreateAudioCapture fail"));
	}
	
}

void UXGAudioCaptureSubsystem::Deinitialize()
{
	Super::Deinitialize();
}

void UXGAudioCaptureSubsystem::Tick(float DeltaTime)
{
}

bool UXGAudioCaptureSubsystem::IsTickable() const
{
	return FTickableGameObject::IsTickable();
}

TStatId UXGAudioCaptureSubsystem::GetStatId() const
{
	RETURN_QUICK_DECLARE_CYCLE_STAT(UXGAudioCaptureSubsystem,STATGROUP_Tickables);
}

//需要优化
void UXGAudioCaptureSubsystem::OnAudioGenerated(const float* InAudio, int32 NumSamples)
{
	LOG_WITH_LOCATION_WARNING(TEXT("OnAudioCapture %f   --  %d"),*InAudio,NumSamples);

	AudioData = const_cast<float*>(InAudio);
	AudioNumSample = NumSamples;
	AudioData = new float[NumSamples];
	for (int32 i = 0; i < NumSamples; ++i)
	{
		AudioData[i] = InAudio[i];
	}
	InAudios.Add(AudioData);
}

bool UXGAudioCaptureSubsystem::GetAudioCaptureDeviceInfo(FAudioCaptureDeviceInfo& OutInfo)
{
	return AudioCapture->GetAudioCaptureDeviceInfo(OutInfo);
}

void UXGAudioCaptureSubsystem::StartCapturingAudio()
{
	if(InAudios.Num()>0)
	{
		for (auto& InAudio : InAudios)
		{
			delete InAudio;
			InAudio = nullptr;
		}
		InAudios.Empty();
	}
	
	AudioCapture->StartCapturingAudio();
}

void UXGAudioCaptureSubsystem::StopCapturingAudio()
{
	AudioCapture->StopCapturingAudio();
}

bool UXGAudioCaptureSubsystem::IsCapturingAudio()
{
	return AudioCapture->IsCapturingAudio();
}
